package chaowan.Controller;

import chaowan.Service.OrderDetailService;
import chaowan.Service.OrderMainService;
import chaowan.pojo.OrderDetail;
import chaowan.pojo.OrderMain;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/orderDetail")
public class OrderDetailController {

    @Resource
    private OrderDetailService orderDetailService;
    @Resource
    private OrderMainService orderMainService;

    @GetMapping("/list/{orderId}")
    public String listByOrderId(@PathVariable Long orderId,
                                @RequestParam(defaultValue = "1") int page,
                                @RequestParam(defaultValue = "10") int size,
                                Model model) {
        OrderMain order = orderMainService.getOrderById(orderId);
        if (order == null) {
            return "redirect:/order/myOrders";
        }

        List<OrderDetail> details = orderDetailService.getDetailsByOrderId(orderId, page, size);
        int totalCount = orderDetailService.getTotalCountByOrderId(orderId);
        int totalPages = (int) Math.ceil((double) totalCount / size);

        model.addAttribute("order", order);
        model.addAttribute("details", details);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages);

        return "order_detail";
    }

    @GetMapping("/addForm")
    public String addForm(Model model) {
        model.addAttribute("detail", new OrderDetail());
        return "orderDetail/add";
    }

    @PostMapping("/add")
    public String add(OrderDetail orderDetail) {
        orderDetailService.save(orderDetail);
        return "redirect:/orderDetail/list";
    }

    @GetMapping("/editForm/{detailId}")
    public String editForm(@PathVariable Long detailId, Model model) {
        OrderDetail detail = orderDetailService.getDetailById(detailId);
        model.addAttribute("detail", detail);
        return "orderDetail/edit";
    }

    @PostMapping("/update")
    public String update(OrderDetail orderDetail) {
        orderDetailService.update(orderDetail);
        return "redirect:/orderDetail/list";
    }

    @GetMapping("/delete/{detailId}")
    public String delete(@PathVariable Long detailId) {
        orderDetailService.deleteById(detailId);
        return "redirect:/orderDetail/list";
    }
}